<template>
  <div class="app-container">
    <el-card class="box-card main-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="title">{{ templeInfo.templeName }}</span>
            <!-- <el-tag type="success" class="ml-10" effect="dark">宗亲会</el-tag> -->
          </div>
          <el-button type="primary" size="large" @click="handleApply">申请入会</el-button>
        </div>
      </template>
      
      <!-- 宗亲会信息 -->
      <div class="section info-section">
        <div class="section-header">
          <h2>
            <i class="el-icon-info"></i> 
            宗亲会信息
            <el-link type="primary" @click="handleInfo">点击查看</el-link>
          </h2>
          <div class="divider"></div>
        </div>
        <el-descriptions :column="1" border class="descriptions">
          <el-descriptions-item label="位置" label-width="120px">
            <i class="el-icon-location-outline"></i> {{ templeInfo.location }}
          </el-descriptions-item>
          <el-descriptions-item label="简介" label-width="120px">
            <!-- <div class="history-content">{{ templeInfo.history }}</div> -->
            <!-- 解析html元素：此处为宗亲会简介内容，支持换行显示 -->
            <div v-html="templeInfo.history"></div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <!-- 荣誉墙 -->
      <div class="section">
        <div class="section-header">
          <h2><i class="el-icon-trophy"></i> 荣誉墙</h2>
          <div class="divider"></div>
        </div>
        <el-row :gutter="24" class="honor-wall">
          <el-col
            v-for="(member, idx) in honorMembers"
            :key="idx"
            :xs="12" :sm="8" :md="6" :lg="4" :xl="4"
            class="member-col"
            @mouseenter="hoverIndex = idx"
            @mouseleave="hoverIndex = -1"
          >
            <el-card shadow="hover" class="honor-card">
              <div class="member-card">
                <div class="avatar-container">
                  <el-avatar :size="80" :src="member.photoUrl" />
                  <div class="position-badge">{{ member.position }}</div>
                  <el-button
                    v-if="hoverIndex === idx"
                    class="edit-btn"
                    type="primary"
                    size="small"
                    style="position: absolute; right: 0; top: 0; z-index: 2;"
                    @click.stop="handleEditMemberCard(member, idx)"
                  >编辑</el-button>
                </div>
                <h3>{{ member.name }}</h3>
                <div class="company">{{ member.companyName }}</div>
                <div class="job-title">{{ member.companyPosition }}</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <!-- 编辑弹窗 -->
      <el-dialog v-model="editDialogVisible" title="编辑成员" width="400px">
        <el-form :model="editMember" label-width="80px">
          <el-form-item label="头像">
            <SingleImageUpload v-model:modelValue="editMember.photoUrl" :style="{width: '120px', height: '120px'}" />
          </el-form-item>
          <el-form-item label="职位">
            <el-select 
              v-model="editMember.position" 
              placeholder="请选择职位" 
              style="width: 100%"
              clearable
              filterable
            >
              <el-option
                v-for="position in positionList"
                :key="position.id"
                :label="position.name"
                :value="position.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="editMember.name" />
          </el-form-item>
          <el-form-item label="公司">
            <el-input v-model="editMember.companyName" />
          </el-form-item>
          <el-form-item label="职务">
            <el-input v-model="editMember.companyPosition" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEditMember">保存</el-button>
        </template>
      </el-dialog>
      
      <!-- 宗亲会信息详情对话框 -->
      <el-dialog v-model="infoDialogVisible" title="宗亲会详细信息" width="60%" top="5vh">
        <div class="info-dialog-content">
          <el-row :gutter="20">
              <div class="info-section">
                <h3><i class="el-icon-info"></i> 基本信息</h3>
                <el-descriptions :column="1" border>
                  <el-descriptions-item label="宗亲会名称" label-width="120px">
                    {{ templeInfo.templeName }}
                  </el-descriptions-item>
                  <el-descriptions-item label="位置" label-width="120px">
                    <i class="el-icon-location-outline"></i> {{ templeInfo.location }}
                  </el-descriptions-item>
                  <el-descriptions-item label="地理位置" label-width="120px">
                    <div class="map-container">
                                             <AmapPicker 
                         v-model:longitude="templeInfo.longitude"
                         v-model:latitude="templeInfo.latitude"
                         :readonly="true"
                         :style="{height: '200px'}"
                       />
                      <!-- <div class="map-info">
                        <p><strong>地址:</strong> {{ templeInfo.location || '暂无' }}</p>
                        <p><strong>经度:</strong> {{ templeInfo.longitude || '暂无' }}</p>
                        <p><strong>纬度:</strong> {{ templeInfo.latitude || '暂无' }}</p>
                      </div> -->
                    </div>
                  </el-descriptions-item>
                  <el-descriptions-item label="简介" label-width="120px">
                    <WangEditor 
                      v-model="templeInfo.history" 
                      :readonly="true"
                      :style="{height: '400px'}"
                    />
                  </el-descriptions-item>
                </el-descriptions>
              </div>
          </el-row>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="infoDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import router from "@/router";
import SingleImageUpload from '@/components/Upload/SingleImageUpload.vue';
import ClanAssociationAPI from "@/api/clan/clan-association.js"
import AmapPicker from "@/components/Map/AmapPicker.vue"
import WangEditor from "@/components/WangEditor/index.vue"
import ClanMemberAPI from "@/api/clanMember/clanMember.js"
import PositionAPI from "@/api/position/position.js"
const route = useRoute()
const templeId = route.params.id

// 荣誉墙成员数据
const honorMembers = ref([])
const hoverIndex = ref(-1)
const editDialogVisible = ref(false)
const editMember = ref({})
const infoDialogVisible = ref(false)
const clanMemberId = ref(null)
// 宗亲会信息
const templeInfo = ref({})

// 职位列表
const positionList = ref([])

// 打开申请对话框
const handleApply = () => {
  router.push({ name: "Application", params: { societyId: 1 } });
}

// 打开宗亲会信息
const handleInfo = () => {
  infoDialogVisible.value = true
}

// 编辑按钮点击
function handleEditMemberCard(member, idx) {
  // 确保member对象包含正确的id字段
  const memberData = {
    ...member,
    id: member.clanMemberId || member.id
  }
  editMember.value = memberData
  editDialogVisible.value = true
}
// 保存编辑
function saveEditMember() {
  // 创建要保存的数据对象
  const saveData = {
    ...editMember.value
  }
  
  // 确保使用id字段
  if (saveData.clanMemberId && !saveData.id) {
    saveData.id = saveData.clanMemberId
  }
  
  // 删除clanMemberId字段，避免重复
  delete saveData.clanMemberId
  
  ClanMemberAPI.update(saveData.id, saveData).then(res => {
    console.log(res);
    editDialogVisible.value = false
    ElMessage.success('编辑成功')
    getMyclan()
  })
}

// 获取宗亲会信息
function getMyclan() {
  ClanAssociationAPI.getMyclan().then(res => {
    if (res) {
      // 将获取到的宗亲会信息赋值到页面中
      templeInfo.value = {
        templeName: res.name || '江西博阳李氏宗亲会',
        location: res.location || '福建省厦门市思明区某某路123号',
        history: res.history || '这是一个具有悠久历史的宗亲会，始建于1900年，经过多代人的传承和发展，现已成为本地区最具影响力的宗亲组织之一。宗亲会致力于弘扬传统文化，增进宗亲情谊，促进社会和谐。',
        longitude: res.longitude,
        latitude: res.latitude
      }
      // 将memberList数据赋值给荣誉墙
      if (res.memberList && Array.isArray(res.memberList)) {
        honorMembers.value = res.memberList.map(member => ({
          id: member.clanMemberId, // 添加id字段
          clanMemberId: member.clanMemberId,
          photoUrl: member.photoUrl || '/src/assets/avatar/unknown.png',
          position: member.position || '会员',
          name: member.clanMemberName || '未知用户',
          companyName: member.companyName || '未知公司',
          companyPosition: member.companyPosition || '未知公司职务'
        }))
      }
    }
  }).catch(error => {
    console.error('获取宗亲会信息失败：', error)
    ElMessage.error('获取宗亲会信息失败')
  })
}

// 获取职位列表
function getPositionList() {
  PositionAPI.getPage().then(res => {
    if (res && res.list) {
      positionList.value = res.list;
      console.log('职位列表加载成功:', positionList.value)
    } else {
      console.warn('职位列表数据为空')
      positionList.value = []
    }
  }).catch(error => {
    console.error('获取职位列表失败：', error)
    ElMessage.error('获取职位列表失败')
    positionList.value = []
  })
}


onMounted(() => {
  getMyclan()
  getPositionList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.main-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.header-left {
  display: flex;
  align-items: center;
}

.title {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.ml-10 {
  margin-left: 10px;
}

.section {
  margin-top: 40px;
}

.section:first-child {
  margin-top: 20px;
}

.section-header {
  position: relative;
  margin-bottom: 25px;
}

.section h2 {
  font-size: 22px;
  color: #303133;
  font-weight: 600;
  margin-bottom: 10px;
  display: inline-block;
}

.divider {
  height: 3px;
  width: 60px;
  background-color: #409EFF;
  margin-bottom: 15px;
}

.descriptions {
  margin-top: 15px;
}

.history-content {
  line-height: 1.8;
  color: #606266;
  text-align: justify;
}

.honor-wall {
  margin-top: 20px;
}

.member-col {
  margin-bottom: 20px;
}

.honor-card {
  transition: all 0.3s;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.honor-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}

.member-card {
  text-align: center;
  padding: 20px 10px;
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-bottom: 15px;
}

.position-badge {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  background-color: #409EFF;
  color: white;
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
  white-space: nowrap;
}

.member-card h3 {
  margin: 10px 0 5px;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.company {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 5px;
}

.job-title {
  color: #909399;
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 5px;
}

.edit-btn {
  position: absolute;
  right: 0;
  top: 0;
  z-index: 2;
  opacity: 0.9;
}

@media screen and (max-width: 768px) {
  .title {
    font-size: 22px;
  }
  
  .section h2 {
    font-size: 18px;
  }
  
  .member-card h3 {
    font-size: 16px;
  }
  
  .company {
    font-size: 12px;
  }
  
  .job-title {
    font-size: 11px;
  }
}

/* 信息对话框样式 */
.info-dialog-content {
  max-height: 70vh;
  overflow-y: auto;
}

.info-section {
  margin-bottom: 20px;
}

.info-section h3 {
  font-size: 18px;
  color: #303133;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-section h3 i {
  margin-right: 8px;
  color: #409EFF;
}

.map-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.map-container :deep(.amap-container) {
  height: 200px !important;
  width: 100% !important;
}

.map-info {
  font-size: 14px;
  color: #606266;
  margin-top: 10px;
}

.map-info p {
  margin: 5px 0;
}


</style>
